package com.hui.dbmigrator.service;

import com.hui.dbmigrator.entity.DatabaseColumnMapping;
import com.hui.dbmigrator.entity.DatabaseTableInfo;
import com.hui.dbmigrator.repository.ColumnMappingRepository;
import com.hui.dbmigrator.repository.TableInfoRepository;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

// TypeConversionService.java
@Service
@RequiredArgsConstructor
public class TypeConversionService {

    private final TableInfoRepository tableInfoRepo;
    private final ColumnMappingRepository mappingRepo;

    public String convertType(String sourceType, String sourceDb, String targetDb) {
        // 1. 尝试精确匹配
        Optional<DatabaseColumnMapping> exactMatch = mappingRepo.findExactMapping(
                sourceDb, targetDb, sourceType);

        if (exactMatch.isPresent()) {
            return exactMatch.get().getTargetColumnType();
        }

        // 2. 尝试基础类型匹配
        String baseType = extractBaseType(sourceType);
        Optional<DatabaseColumnMapping> baseMatch = mappingRepo.findExactMapping(
                sourceDb, targetDb, baseType);

        if (baseMatch.isPresent()) {
            return applyLengthAndPrecision(
                    baseMatch.get().getTargetColumnType(),
                    sourceType,
                    targetDb);
        }

        // 3. 默认返回原类型（带警告）
        return sourceType;
    }

    private String extractBaseType(String typeDefinition) {
        // 从VARCHAR(255)中提取VARCHAR
        if (typeDefinition.contains("(")) {
            return typeDefinition.substring(0, typeDefinition.indexOf("("));
        }
        return typeDefinition;
    }

    private String applyLengthAndPrecision(String targetType, String sourceType, String targetDb) {
        // 处理带长度/精度的类型转换
        if (!sourceType.contains("(") || !targetType.contains("(")) {
            return targetType;
        }

        // 获取源类型的长度/精度
        String sourceParams = sourceType.substring(sourceType.indexOf("(") + 1,
                sourceType.lastIndexOf(")"));

        // 获取目标类型的参数位置
        String targetBase = targetType.substring(0, targetType.indexOf("("));
        String targetPattern = targetType.substring(targetType.indexOf("("));

        // 替换参数
        String converted = targetBase + targetPattern.replace("?", sourceParams);
        return converted;
    }

    public void validateType(String dbType, String columnType) {
        QueryWrapper query = QueryWrapper.create()
                .eq(DatabaseTableInfo::getColumnType, extractBaseType(columnType))
                .eq(DatabaseTableInfo::getDbType, dbType);
        DatabaseTableInfo typeInfo = tableInfoRepo.selectOneByQuery(query);

        if (typeInfo == null) {
            throw new IllegalArgumentException("Unsupported column type: " + columnType);
        }

        // 验证长度限制
        if ("1".equals(typeInfo.getColumnNeedLength())) {
            int length = extractLength(columnType);
            if (length > typeInfo.getColumnMaxLength()) {
                throw new IllegalArgumentException(
                        "Length exceeds maximum allowed value: " + length + " > " +
                                typeInfo.getColumnMaxLength());
            }
        }
    }

    private int extractLength(String columnType) {
    }

    // 其他辅助方法...
}
